package main

import (
	"context"
	"errors"
	"net/http"
	"os"
	"os/signal"
	"smart-flow/server/config"
	"smart-flow/server/controller"
	"smart-flow/server/executor"
	"smart-flow/server/ips"
	"smart-flow/server/logger"
	"smart-flow/server/middleware"
	"smart-flow/server/net"
	"smart-flow/server/redis"
	"smart-flow/server/region"
	"smart-flow/server/service"
	"smart-flow/server/task"
	"strconv"
	"syscall"
	"time"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func init() {
	config.LoadConfig("./resource")
	logger.InitLogger(config.AppConfig().Log.LogPath, config.AppConfig().Server.Mode)
	redis.InitRedisPool(config.AppConfig().Redis)
	net.InitConsoleClients()
	region.InitSearcher("./resource/ip2region.xdb")
	ips.InitIps("./resource/cm-ips.conf")
	executor.InitExecutor()
	service.InitDispatcher()
	task.InitTask()
}

func main() {
	serverInit()
}

func engineInit() *gin.Engine {
	// 创建默认的 Gin 引擎实例
	gin.SetMode(config.AppConfig().Server.Mode)
	r := gin.New()
	// r.SetTrustedProxies([]string{"172.16.0.0/16"})
	_ = r.SetTrustedProxies(nil)
	// 添加 CORS 中间件，允许所有来源的跨域请求, 添加安全 Header 中间件
	r.Use(gin.Logger(), gin.Recovery(), middleware.AllowCors(), middleware.SecureHeader())
	// 加载静态资源和模板文件夹
	r.LoadHTMLGlob("view/*.html")
	r.Static("/assets", "./public/assets")
	if config.AppConfig().Server.Mode == gin.DebugMode {
		r.Static("/download", "../release")
	}

	// 定义路由
	r.GET("/sf/", welcome)

	r.GET("/sf/Home", controller.Home)
	r.POST("/sf/Login", controller.Login)

	r.GET("/sf/Flow/Index", controller.Index)
	r.GET("/sf/Flow/Count", controller.Count)
	r.GET("/sf/Flow/Bandwidth", controller.Bandwidth)
	r.POST("/sf/Flow/Stop", controller.Stop)
	r.POST("/sf/Flow/StopOne", controller.StopOne)
	r.POST("/sf/Flow/Test", controller.Test)
	r.POST("/sf/Flow/Start", controller.Start)

	r.GET("/sf/Task/List", controller.TaskList)
	r.POST("/sf/Task/Add", controller.AddTask)
	r.POST("/sf/Task/Del", controller.DelTask)
	r.POST("/sf/Task/GlobalPause", controller.GlobalPause)
	r.POST("/sf/Task/GlobalResume", controller.GlobalResume)

	r.POST("/sf/monitor/exchange", controller.Exchange)

	r.POST("sf/Test/GetUid", controller.GetUidByIp)
	return r
}
func serverInit() {
	srv := &http.Server{
		Addr:    ":" + strconv.Itoa(config.AppConfig().Server.Port),
		Handler: engineInit(),
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			logger.Logger.Error("[系统] 服务启动失败", zap.Error(err))
			os.Exit(1)
		}
	}()
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	logger.Logger.Info("[系统] 服务关闭中...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	service.ShutdownDispatcher()
	time.Sleep(time.Second)
	net.DisConnectConsoleServers()
	time.Sleep(time.Second)
	if err := srv.Shutdown(ctx); err != nil {
		logger.Logger.Error("[系统] 服务关闭异常", zap.Error(err))
	}
	logger.Logger.Info("[系统] 服务已退出")
}

func welcome(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Hello Developer, Welcome!",
	})
}
